from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Order
from products.models import Product

@receiver(post_save, sender=Order)
def update_product_status_on_order_change(sender, instance, **kwargs):
    """
    监听订单状态变化,自动更新商品状态
    """
    product = instance.product
    
    # 如果订单被取消,将商品状态恢复为已上架
    if instance.status == 4:  # 已取消
        if product.status == 2:  # 只有在商品是交易中状态时才恢复
            product.status = 1  # 恢复为已上架
            product.save(update_fields=['status'])
    
    # 如果订单支付成功,将商品状态改为交易中
    elif instance.status == 1:  # 待发货(已支付)
        product.status = 2  # 设置为交易中
        product.save(update_fields=['status'])